package com.ailot.cloud.upms.api.controller;

import com.ailot.cloud.base.common.constants.CommonConstant;
import com.ailot.cloud.upms.api.service.SysOrgService;
import com.ailot.cloud.upms.common.dto.OrgTree;
import com.ailot.cloud.upms.common.entity.SysOrg;
import com.ailot.cloud.upms.common.utils.TreeUtil;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import lombok.AllArgsConstructor;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.*;

import javax.validation.Valid;
import java.util.List;
import java.util.stream.Collectors;

/**
 * 机构管理
 */
@RestController
@AllArgsConstructor
@RequestMapping("/org")
public class SysOrgController {

    private final SysOrgService sysOrgService;

    @GetMapping("/{id}")
    @PreAuthorize("hasAuthority('sys:org:get')")
    public SysOrg getById(@PathVariable String id) {
        return sysOrgService.getById(id);
    }

    @GetMapping("/list")
    public List<SysOrg> getList(SysOrg sysorg) {
        return sysOrgService.list(Wrappers.query(sysorg));
    }

    @GetMapping(value = "/tree")
    public List<OrgTree> getTree() {
        List<SysOrg> sysOrgList = sysOrgService.list();
        List<OrgTree> orgTreeList = sysOrgList.stream()
                .map(OrgTree::new)
                .collect(Collectors.toList());
        return TreeUtil.build(orgTreeList, CommonConstant.PARENT_ID);

    }

    @PostMapping
    @PreAuthorize("hasAuthority('sys:org:add')")
    public Boolean add(@Valid @RequestBody SysOrg sysOrg) {
        return sysOrgService.save(sysOrg);
    }

    @DeleteMapping("/{id}")
    @PreAuthorize("hasAuthority('sys:org:del')")
    public Boolean delete(@PathVariable String id) {
        return sysOrgService.removeById(id);
    }


    @PutMapping
    @PreAuthorize("hasAuthority('sys:org:edit')")
    public Boolean update(@Valid @RequestBody SysOrg sysOrg) {
        return sysOrgService.updateById(sysOrg);
    }

}


